package cn.iocoder.yudao.module.asasc.service.campaign;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.asasc.controller.admin.campaign.vo.CampaignGrandTotalsPageReqVO;
import cn.iocoder.yudao.module.asasc.controller.admin.campaign.vo.CampaignGrandTotalsSaveReqVO;
import cn.iocoder.yudao.module.asasc.dal.dataobject.campaign.CampaignGrandTotalsDO;
import cn.iocoder.yudao.module.asasc.dal.mysql.campaign.CampaignGrandTotalsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.asasc.enums.ErrorCodeConstants.CAMPAIGN_GRAND_TOTALS_NOT_EXISTS;

/**
 * 广告数据汇总 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class CampaignGrandTotalsServiceImpl implements CampaignGrandTotalsService {

    @Resource
    private CampaignGrandTotalsMapper campaignGrandTotalsMapper;

    @Override
    public Long createCampaignGrandTotals(CampaignGrandTotalsSaveReqVO createReqVO) {
        // 插入
        CampaignGrandTotalsDO campaignGrandTotals = BeanUtils.toBean(createReqVO, CampaignGrandTotalsDO.class);
        if (Objects.isNull(campaignGrandTotals.getCreator())) {
            campaignGrandTotals.setCreator("System");
            campaignGrandTotals.setDeleted(false);
            campaignGrandTotals.setTenantId(1L);
        }
        campaignGrandTotalsMapper.insert(campaignGrandTotals);
        // 返回
        return campaignGrandTotals.getId();
    }

    @Override
    public void updateCampaignGrandTotals(CampaignGrandTotalsSaveReqVO updateReqVO) {
        // 校验存在
        validateCampaignGrandTotalsExists(updateReqVO.getId());
        // 更新
        CampaignGrandTotalsDO updateObj = BeanUtils.toBean(updateReqVO, CampaignGrandTotalsDO.class);
        campaignGrandTotalsMapper.updateById(updateObj);
    }

    @Override
    public void updateOrSaveGrandTotalsByDateAndAdamId(CampaignGrandTotalsSaveReqVO updateReqVO) {
        CampaignGrandTotalsDO updateObj = BeanUtils.toBean(updateReqVO, CampaignGrandTotalsDO.class);
        int updateCount = 0;

        try {
            updateCount = campaignGrandTotalsMapper.updateGrandTotalsByDateAndAdamId(updateObj);
        } catch (Exception e) {
            log.error("updateOrSaveGrandTotalsByDateAndAdamId update failed: {}", e.getMessage());
        }

        if (updateCount == 0) {
            // 更新失败，执行插入操作
            try {
                campaignGrandTotalsMapper.insert(updateObj);
                //log.info("Insert successful for: {}", updateObj);
            } catch (Exception e) {
                log.error("updateOrSaveGrandTotalsByDateAndAdamId insert failed: {}", e.getMessage());
                throw e; // 重新抛出异常或根据需要处理
            }
        }
    }

    @Override
    public void deleteCampaignGrandTotals(Long id) {
        // 校验存在
        validateCampaignGrandTotalsExists(id);
        // 删除
        campaignGrandTotalsMapper.deleteById(id);
    }

    private void validateCampaignGrandTotalsExists(Long id) {
        if (campaignGrandTotalsMapper.selectById(id) == null) {
            throw exception(CAMPAIGN_GRAND_TOTALS_NOT_EXISTS);
        }
    }

    @Override
    public CampaignGrandTotalsDO getCampaignGrandTotals(Long id) {
        return campaignGrandTotalsMapper.selectById(id);
    }

    @Override
    public PageResult<CampaignGrandTotalsDO> getCampaignGrandTotalsPage(CampaignGrandTotalsPageReqVO pageReqVO) {
        PageResult<CampaignGrandTotalsDO> result = campaignGrandTotalsMapper.selectPage(pageReqVO);
        for (CampaignGrandTotalsDO cgt : result.getList()) {
            //计算试订率
            if (cgt.getAscInstalls() != null && cgt.getAscInstalls() != 0 && cgt.getAscTrial() != null) {
                cgt.setTrialRate(BigDecimal.valueOf(cgt.getAscTrial()).divide(BigDecimal.valueOf(cgt.getAscInstalls()), 4, RoundingMode.HALF_UP));
            } else {
                cgt.setTrialRate(BigDecimal.ZERO);
            }
        }
        return result;
    }

}